package com.edoomath.api.handler.impl;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.http.annotation.Rao;
import com.demo2do.core.utils.JsonUtils;
import com.edoomath.api.handler.QiniuHandler;
import com.edoomath.api.rao.QiniuRao;

/**
 * 
 * @author mohanlan
 *
 */
@Component("qiniuHandler")
public class QiniuHandlerImpl implements QiniuHandler {
	
	@Value("#{cloud['cloud.qiniu.domain']}")
    private String qiniuDomain;
	
	@Value("#{cloud['cloud.qiniu.host']}")
    private String qiniuHost;
    
    private static final String GENERATE_QRCODE_URI = "/generate-qrcode";
    
    private static final Logger logger = LoggerFactory.getLogger(QiniuHandler.class);
    
    @Rao
    private QiniuRao qiniuRao;

    /*
     * (non-Javadoc)
     * @see com.edoomath.admin.handler.QrcodeHandler#generateQrCode(java.lang.String)
     */
    public String generateQrCode(String url) {
        return generateQrCode(null, url);
    }

    /*
     * (non-Javadoc)
     * @see com.edoomath.admin.handler.QrcodeHandler#generateQrCode(java.lang.String, java.lang.String)
     */
    public String generateQrCode(String bucket, String url) {
        
    	HttpResult result = null;
            
        Map<String, Object> parameters = new HashMap<String, Object>();
        
        parameters.put("url", url);
        if(bucket != null) {
            parameters.put("bucket", bucket);
        }
        
        result = qiniuRao.generateQrcode(qiniuDomain + GENERATE_QRCODE_URI, parameters);
        logger.trace("generateQrCode() - Get result [{}]", JsonUtils.toJson(result));
        
        logger.trace("generateQrCode() - Get result key [" + result.getData().get("key").toString() + "].");
        
        if ( result.isValid() ) {
            String qrcode = result.getData().get("key").toString();
            return com.demo2do.core.utils.StringUtils.connect(qiniuHost, "/", qrcode);
        } else {
        	logger.trace("generateQrCode() - Get result [{}]", JsonUtils.toJson(result));
            throw new BusinessException("生成二维码失败");
        }

    }

}
